/**
 * 视频信息提取器 - 简化版本
 * 专注于基础视频信息提取，支持两种API模式
 */

class VideoExtractor {
    constructor() {
        this.form = document.getElementById('videoForm');
        this.urlInput = document.getElementById('videoUrl');
        this.submitButton = document.getElementById('submitButton');
        this.buttonText = this.submitButton.querySelector('.button-text');
        this.buttonLoading = this.submitButton.querySelector('.button-loading');
        this.resultsSection = document.getElementById('resultsSection');
        this.resultContent = document.getElementById('resultContent');
        
        // 状态管理
        this.currentVideoUrl = '';
        this.currentTaskId = null;
        this.pollInterval = null;
        
        this.init();
    }

    init() {
        // 绑定事件监听器
        this.form.addEventListener('submit', this.handleSubmit.bind(this));
        this.urlInput.addEventListener('input', this.handleInputChange.bind(this));
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideResults();
            }
        });
        
        console.log('视频提取器初始化完成');
    }

    handleInputChange() {
        // 实时验证是否包含有效的URL
        const inputText = this.urlInput.value.trim();
        const hasValidUrl = this.extractUrlFromText(inputText) !== null;
        
        this.urlInput.classList.toggle('invalid', inputText && !hasValidUrl);
    }

    async handleSubmit(e) {
        e.preventDefault();
        
        const inputText = this.urlInput.value.trim();
        
        if (!inputText) {
            this.showError('请输入视频链接或包含链接的分享文本');
            return;
        }

        const extractedUrl = this.extractUrlFromText(inputText);
        if (!extractedUrl) {
            this.showError('未找到有效的视频链接，请检查输入内容');
            return;
        }

        this.currentVideoUrl = extractedUrl;
        
        try {
            this.setLoading(true);
            
            // 首先尝试基础信息API（免费）
            const basicInfo = await this.getBasicInfo(extractedUrl);
            
            if (basicInfo) {
                this.displayResults(basicInfo);
                this.showResults();
                
                // 跟踪事件
                this.trackEvent('video_basic_info', 'extraction', this.getPlatformFromUrl(extractedUrl));
            } else {
                // 如果基础API失败，尝试完整API（消耗积分）
                await this.getCompleteInfo(extractedUrl);
            }
        } catch (error) {
            console.error('提取视频信息失败:', error);
            this.showError(error.message || '网络错误，请稍后重试');
        } finally {
            this.setLoading(false);
        }
    }

    // 获取基础信息（免费API）
    async getBasicInfo(url) {
        try {
            // 获取JWT ticket
            const ticketResponse = await fetch('/api/tkt/get_ticket');
            if (!ticketResponse.ok) {
                throw new Error('获取访问令牌失败');
            }
            
            const ticketData = await ticketResponse.json();
            const ticket = ticketData.ticket;
            
            // 构造请求数据
            const requestData = {
                url: url,
                extract_text: false // 仅获取基础信息
            };
            
            // 加密数据
            const encryptedData = this.encryptData(JSON.stringify(requestData), ticket);
            
            // 调用基础信息API
            const response = await fetch('/api/media/e1/bsc', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Ticket': ticket
                },
                body: JSON.stringify(encryptedData)
            });

            if (!response.ok) {
                return null; // 失败则返回null，让调用方尝试完整API
            }

            const result = await response.json();
            console.log('基础信息API响应:', result);
            
            if (result.code === 200) {
                console.log('基础信息数据:', result.data);
                return result.data;
            } else {
                console.log('基础信息API失败:', result);
                return null;
            }
        } catch (error) {
            console.error('获取基础信息失败:', error);
            return null;
        }
    }

    // 获取完整信息（消耗积分的API）
    async getCompleteInfo(url) {
        try {
            const requestData = {
                url: url,
                extract_text: false, // 不提取文案，只要基础信息
                include_comments: false
            };

            const response = await fetch('/api/media/extract/web', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Auth-Key': 'web-frontend-api-key-2025' // 使用专用Web API密钥
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }

            const result = await response.json();
            
            if (result.code === 200) {
                // 同步返回结果
                this.displayResults(result.data);
                this.showResults();
                this.trackEvent('video_complete_info', 'extraction', this.getPlatformFromUrl(url));
            } else if (result.code === 202) {
                // 异步任务，开始轮询
                this.currentTaskId = result.data.task_id;
                this.startTaskPolling();
                this.trackEvent('video_async_task', 'start', this.getPlatformFromUrl(url));
            } else {
                throw new Error(result.msg || '获取视频信息失败');
            }
        } catch (error) {
            console.error('获取完整信息失败:', error);
            throw error;
        }
    }

    // 轮询任务状态
    async pollTaskStatus(taskId) {
        try {
            const response = await fetch(`/api/media/extract/web/status/${taskId}`, {
                headers: {
                    'X-Auth-Key': 'web-frontend-api-key-2025'
                }
            });

            if (!response.ok) {
                throw new Error(`状态查询失败: ${response.status}`);
            }

            const result = await response.json();
            return result;
        } catch (error) {
            console.error('查询任务状态失败:', error);
            throw error;
        }
    }

    // 开始任务轮询
    startTaskPolling() {
        this.showTaskProgress();
        
        // 轮询任务状态 - 每2秒轮询一次
        this.pollInterval = setInterval(async () => {
            try {
                const result = await this.pollTaskStatus(this.currentTaskId);
                
                // 添加防御性检查，确保result存在
                if (!result) {
                    console.error('轮询返回空结果');
                    return;
                }
                
                if (result.code === 200 && result.status === 'completed') {
                    // 任务完成
                    clearInterval(this.pollInterval);
                    this.pollInterval = null; // 确保清除
                    this.hideTaskProgress();
                    this.displayResults(result.data);
                    this.showResults();
                    
                    // 完成跟踪
                    this.trackEvent('video_async_task', 'completed', this.getPlatformFromUrl(this.currentVideoUrl));
                } else if (result.status === 'failed') {
                    // 任务失败
                    clearInterval(this.pollInterval);
                    this.pollInterval = null; // 确保清除
                    this.hideTaskProgress();
                    this.showError('视频信息提取失败，请稍后重试');
                }
            } catch (error) {
                console.error('轮询任务状态失败:', error);
                // 在网络错误时不停止轮询，让其继续尝试
            }
        }, 2000);

        // 5分钟超时
        setTimeout(() => {
            if (this.pollInterval) {
                clearInterval(this.pollInterval);
                this.hideTaskProgress();
                this.showError('提取超时，请稍后重试');
            }
        }, 5 * 60 * 1000);
    }

    // 显示任务进度
    showTaskProgress(title = '正在提取视频信息...', description = '请耐心等待，我们正在为您获取详细的视频信息') {
        this.resultContent.innerHTML = `
            <div class="task-progress">
                <div class="progress-content">
                    <div class="progress-icon">
                        <svg class="progress-spinner" viewBox="0 0 50 50" width="50" height="50">
                            <circle cx="25" cy="25" r="20" fill="none" stroke="#667eea" stroke-width="4" stroke-dasharray="31.416" stroke-dashoffset="31.416" stroke-linecap="round">
                                <animate attributeName="stroke-array" dur="2s" values="0 31.416;15.708 15.708;0 31.416" repeatCount="indefinite"/>
                                <animate attributeName="stroke-dashoffset" dur="2s" values="0;-15.708;-31.416" repeatCount="indefinite"/>
                            </circle>
                        </svg>
                    </div>
                    <div class="progress-text">
                        <h3>${this.escapeHtml(title)}</h3>
                        <p>${this.escapeHtml(description)}</p>
                    </div>
                </div>
            </div>
        `;
        this.showResults();
    }

    // 隐藏任务进度
    hideTaskProgress() {
        // 进度会被结果替换，这里可以清理相关状态
        if (this.pollInterval) {
            clearInterval(this.pollInterval);
            this.pollInterval = null;
        }
    }

    // 显示结果
    displayResults(data, showTextButton = true) {
        const {
            title = '未知标题',
            description = '暂无描述',
            author = {},
            media = {},
            statistics = {},
            tags = [],
            publish_time = '未知时间',
            platform = 'unknown',
            text_content = null, // 文案内容（前端字段名）
            content = null // 后端返回的文案字段名
        } = data;
        
        // 字段映射：优先使用text_content，如果没有则使用content
        const finalTextContent = text_content || content;

        this.resultContent.innerHTML = `
            <div class="video-result-card">
                <!-- 视频封面和主要信息 -->
                <div class="video-header">
                    <div class="video-cover-container">
                        ${media.cover_url ? `
                            <img src="${this.escapeHtml(media.cover_url)}" 
                                 alt="视频封面" 
                                 class="video-cover"
                                 loading="lazy">
                            <div class="cover-overlay">
                                ${media.video_url ? `
                                    <a href="/static/player.html?video_url=${encodeURIComponent(media.video_url)}&original_url=${encodeURIComponent(this.currentVideoUrl)}" 
                                       target="_blank" 
                                       class="play-button"
                                       title="下载视频">
                                        <svg viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M8 5v14l11-7z"/>
                                        </svg>
                                    </a>
                                ` : ''}
                            </div>
                        ` : `
                            <div class="video-cover-placeholder">
                                <div class="placeholder-icon">🎬</div>
                                <div class="placeholder-text">暂无封面</div>
                            </div>
                        `}
                    </div>
                    
                    <div class="video-meta-info">
                        <h2 class="video-title">${this.escapeHtml(title)}</h2>
                        
                        ${author.nickname ? `
                            <div class="author-info">
                                <div class="author-avatar">
                                    ${author.avatar ? `
                                        <img src="${this.escapeHtml(author.avatar)}" alt="作者头像">
                                    ` : `
                                        <div class="avatar-placeholder">${this.escapeHtml(author.nickname.charAt(0))}</div>
                                    `}
                                </div>
                                <div class="author-details">
                                    <div class="author-name">${this.escapeHtml(author.nickname)}</div>
                                    ${author.signature ? `
                                        <div class="author-signature">${this.escapeHtml(author.signature)}</div>
                                    ` : ''}
                                </div>
                            </div>
                        ` : ''}
                        
                        <!-- 视频统计数据 -->
                        <div class="video-stats">
                            ${statistics.play_count ? `
                                <div class="stat-item">
                                    <span class="stat-icon">👁️</span>
                                    <span class="stat-value">${this.formatNumber(statistics.play_count)}</span>
                                    <span class="stat-label">播放</span>
                                </div>
                            ` : ''}
                            ${statistics.like_count ? `
                                <div class="stat-item">
                                    <span class="stat-icon">👍</span>
                                    <span class="stat-value">${this.formatNumber(statistics.like_count)}</span>
                                    <span class="stat-label">点赞</span>
                                </div>
                            ` : ''}
                            ${statistics.comment_count ? `
                                <div class="stat-item">
                                    <span class="stat-icon">💬</span>
                                    <span class="stat-value">${this.formatNumber(statistics.comment_count)}</span>
                                    <span class="stat-label">评论</span>
                                </div>
                            ` : ''}
                            ${statistics.share_count ? `
                                <div class="stat-item">
                                    <span class="stat-icon">📤</span>
                                    <span class="stat-value">${this.formatNumber(statistics.share_count)}</span>
                                    <span class="stat-label">分享</span>
                                </div>
                            ` : ''}
                        </div>
                        
                        <!-- 视频描述 -->
                        ${description && description !== '暂无描述' ? `
                            <div class="video-description">
                                <p>${this.escapeHtml(description)}</p>
                            </div>
                        ` : ''}
                        
                        <!-- 标签 -->
                        ${tags && tags.length > 0 ? `
                            <div class="video-tags">
                                ${tags.map(tag => `
                                    <span class="tag">#${this.escapeHtml(tag)}</span>
                                `).join('')}
                            </div>
                        ` : ''}
                        
                        <!-- 文案内容区域 -->
                        ${finalTextContent ? `
                            <div class="video-text-content">
                                <h3 class="text-content-title">视频文案</h3>
                                <div class="text-content-body">
                                    <p>${this.escapeHtml(finalTextContent)}</p>
                                </div>
                            </div>
                        ` : ''}
                        
                        <!-- 播放和文案按钮区域 -->
                        <div class="action-buttons-section">
                            ${media.video_url ? `
                                <a href="/static/player.html?video_url=${encodeURIComponent(media.video_url)}&original_url=${encodeURIComponent(this.currentVideoUrl)}" 
                                   target="_blank" 
                                   class="play-video-btn">
                                    <span class="btn-icon">▶️</span>
                                    <span class="btn-text">下载视频</span>
                                </a>
                            ` : ''}
                            
                            ${showTextButton && !finalTextContent ? `
                                <button class="extract-text-btn" onclick="window.videoExtractor.getVideoText()">
                                    <span class="btn-icon">📝</span>
                                    <span class="btn-text">获取视频文案</span>
                                    <span class="btn-hint">（限免积分）</span>
                                </button>
                            ` : ''}
                        </div>
                        
                        ${showTextButton && !finalTextContent ? `
                            <p class="extract-hint">获取视频的完整文案内容，包括描述文本、字幕等</p>
                        ` : ''}
                        
                        <!-- 发布时间和平台 -->
                        <div class="video-meta-footer">
                            <div class="publish-info">
                                <span class="platform-badge">${this.getPlatformName(platform)}</span>
                                <span class="publish-time">发布于 ${publish_time}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 显示结果区域
    showResults() {
        this.resultsSection.style.display = 'block';
        
        // 平滑滚动到结果区域
        setTimeout(() => {
            this.resultsSection.scrollIntoView({ 
                behavior: 'smooth',
                block: 'start'
            });
        }, 100);
    }

    // 隐藏结果区域
    hideResults() {
        this.resultsSection.style.display = 'none';
        
        // 清理轮询
        if (this.pollInterval) {
            clearInterval(this.pollInterval);
            this.pollInterval = null;
        }
        
        // 重置状态
        this.currentTaskId = null;
    }

    // 设置加载状态
    setLoading(isLoading) {
        this.submitButton.disabled = isLoading;
        this.buttonText.style.display = isLoading ? 'none' : 'inline-flex';
        this.buttonLoading.style.display = isLoading ? 'inline-flex' : 'none';
        
        if (isLoading) {
            this.submitButton.classList.add('loading');
        } else {
            this.submitButton.classList.remove('loading');
        }
    }

    // 显示错误
    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.innerHTML = `
            <div class="error-content">
                <span class="error-icon">⚠️</span>
                <span class="error-text">${this.escapeHtml(message)}</span>
                <button class="error-close" onclick="this.parentElement.parentElement.remove()">×</button>
            </div>
        `;
        
        // 插入到表单后面
        this.form.parentNode.insertBefore(errorDiv, this.form.nextSibling);
        
        // 5秒后自动消失
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.remove();
            }
        }, 5000);
    }

    // 显示成功
    showSuccess(message) {
        const successDiv = document.createElement('div');
        successDiv.className = 'success-message';
        successDiv.innerHTML = `
            <div class="success-content">
                <span class="success-icon">✅</span>
                <span class="success-text">${this.escapeHtml(message)}</span>
                <button class="success-close" onclick="this.parentElement.parentElement.remove()">×</button>
            </div>
        `;
        
        this.form.parentNode.insertBefore(successDiv, this.form.nextSibling);
        
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.remove();
            }
        }, 3000);
    }

    // 从文本中提取URL
    extractUrlFromText(text) {
        const urlRegex = /https?:\/\/[^\s]+/gi;
        const matches = text.match(urlRegex);
        return matches ? matches[0] : null;
    }

    // 获取平台名称
    getPlatformName(platform) {
        const platformNames = {
            'douyin': '抖音',
            'tiktok': 'TikTok',
            'xiaohongshu': '小红书',
            'bilibili': '哔哩哔哩',
            'youtube': 'YouTube',
            'kuaishou': '快手',
            'instagram': 'Instagram',
            'twitter': 'Twitter'
        };
        return platformNames[platform] || platform.toUpperCase();
    }

    // 从URL获取平台
    getPlatformFromUrl(url) {
        if (url.includes('douyin.com')) return 'douyin';
        if (url.includes('tiktok.com')) return 'tiktok';
        if (url.includes('xiaohongshu.com')) return 'xiaohongshu';
        if (url.includes('bilibili.com')) return 'bilibili';
        if (url.includes('youtube.com')) return 'youtube';
        if (url.includes('kuaishou.com')) return 'kuaishou';
        if (url.includes('instagram.com')) return 'instagram';
        if (url.includes('twitter.com')) return 'twitter';
        return 'unknown';
    }

    // 格式化数字
    formatNumber(num) {
        if (typeof num !== 'number') return num;
        if (num >= 10000) {
            return (num / 10000).toFixed(1) + 'w';
        }
        return num.toString();
    }

    // HTML转义
    escapeHtml(text) {
        if (typeof text !== 'string') return text;
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 数据加密
    encryptData(data, ticket) {
        // 基于ticket生成AES密钥 - 与后端保持一致，使用SHA256的原始字节
        const key = CryptoJS.SHA256(ticket);
        const iv = CryptoJS.lib.WordArray.random(16);
        
        // AES加密
        const encrypted = CryptoJS.AES.encrypt(data, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        
        return {
            data: encrypted.toString(),
            iv: CryptoJS.enc.Base64.stringify(iv)
        };
    }

    // 获取视频文案
    async getVideoText() {
        console.log('getVideoText 被调用，currentVideoUrl:', this.currentVideoUrl);
        
        if (!this.currentVideoUrl) {
            this.showError('无法获取文案：没有视频链接');
            return;
        }

        try {
            // 禁用按钮并显示加载状态
            const textBtn = document.querySelector('.extract-text-btn');
            if (textBtn) {
                textBtn.disabled = true;
                textBtn.innerHTML = `
                    <span class="btn-icon">⏳</span>
                    <span class="btn-text">注册任务中...</span>
                `;
            }

            // 注册文案提取任务
            const requestData = {
                url: this.currentVideoUrl,
                extract_text: true, // 获取文案
                include_comments: false
            };

            console.log('发送文案提取请求:', requestData);
            
            const response = await fetch('/api/media/extract/web', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Auth-Key': 'web-frontend-api-key-2025'
                },
                body: JSON.stringify(requestData)
            });

            console.log('文案API响应状态:', response.status);

            if (!response.ok) {
                const errorText = await response.text();
                console.error('文案API错误响应:', errorText);
                throw new Error(`请求失败: ${response.status}`);
            }

            const result = await response.json();
            console.log('文案API响应:', result);
            console.log('响应数据结构:', JSON.stringify(result, null, 2));
            
            if (result.code === 202) {
                // 异步任务注册成功，开始轮询
                // 注意：后端直接返回task_id字段，不是嵌套在data里
                if (!result.task_id) {
                    console.error('API返回202但缺少task_id:', result);
                    throw new Error('任务注册失败：缺少任务ID');
                }
                
                this.currentTaskId = result.task_id;
                console.log('设置任务ID:', this.currentTaskId);
                this.startTextTaskPolling();
                this.trackEvent('video_text_extract', 'task_registered', this.getPlatformFromUrl(this.currentVideoUrl));
            } else if (result.code === 200) {
                // 极少数情况下可能同步返回（快速处理的任务）
                this.displayResults(result.data, false); // 不再显示获取文案按钮
                this.trackEvent('video_text_extract', 'sync_completed', this.getPlatformFromUrl(this.currentVideoUrl));
                this.showSuccess('文案获取成功！');
            } else {
                console.error('API返回非成功状态:', result);
                throw new Error(result.msg || result.message || '获取文案失败');
            }
        } catch (error) {
            console.error('获取文案失败:', error);
            this.showError(error.message || '获取文案失败，请稍后重试');
            this.restoreTextButton(); // 使用统一的恢复函数
        }
    }

    // 轮询文案任务状态
    startTextTaskPolling() {
        console.log('开始文案任务轮询，任务ID:', this.currentTaskId);
        this.showTaskProgress('正在获取视频文案...', '正在为您提取完整的视频文案内容');
        
        // 轮询任务状态 - 每20秒轮询一次
        this.pollInterval = setInterval(async () => {
            console.log('执行文案轮询，任务ID:', this.currentTaskId);
            try {
                const result = await this.pollTaskStatus(this.currentTaskId);
                console.log('轮询结果:', result);
                
                // 添加防御性检查，确保result存在且有状态字段
                if (!result || !result.hasOwnProperty('status')) {
                    console.error('轮询返回无效结果，继续等待下次轮询:', result);
                    return; // 这次轮询失败，等待下次
                }
                
                console.log('任务状态:', result.status);
                
                if (result.code === 200 && result.status === 'completed') {
                    // 任务完成
                    console.log('任务完成，停止轮询');
                    clearInterval(this.pollInterval);
                    this.pollInterval = null; // 确保清除
                    this.hideTaskProgress();
                    
                    // 显示结果，data字段包含完整的媒体信息
                    this.displayResults(result.data, false); // 不再显示获取文案按钮
                    this.showSuccess('文案获取成功！');
                    
                    // 完成跟踪
                    this.trackEvent('video_text_extract', 'completed', this.getPlatformFromUrl(this.currentVideoUrl));
                } else if (result.status === 'failed') {
                    // 任务失败
                    console.log('任务失败，停止轮询');
                    clearInterval(this.pollInterval);
                    this.pollInterval = null; // 确保清除
                    this.hideTaskProgress();
                    this.showError('文案获取失败，请稍后重试');
                    this.restoreTextButton(); // 恢复按钮状态
                } else {
                    console.log('任务还在进行中，继续轮询. 状态:', result.status);
                }
            } catch (error) {
                console.error('轮询文案任务状态失败:', error);
                console.log('网络错误，将在下次轮询时重试');
                // 在网络错误时不停止轮询，让其继续尝试
            }
        }, 20000);

        // 5分钟超时
        setTimeout(() => {
            if (this.pollInterval) {
                clearInterval(this.pollInterval);
                this.hideTaskProgress();
                this.showError('文案获取超时，请稍后重试');
                this.restoreTextButton(); // 恢复按钮状态
            }
        }, 5 * 60 * 1000);
    }

    // 恢复获取文案按钮状态
    restoreTextButton() {
        const textBtn = document.querySelector('.extract-text-btn');
        if (textBtn) {
            textBtn.disabled = false;
            textBtn.innerHTML = `
                <span class="btn-icon">📝</span>
                <span class="btn-text">获取视频文案</span>
                <span class="btn-hint">（限免积分）</span>
            `;
        }
    }

    // 事件跟踪
    trackEvent(action, category, label, value) {
        if (typeof gtag === 'function') {
            gtag('event', action, {
                'event_category': category,
                'event_label': label,
                'value': value
            });
        }
        if (typeof window.trackEvent === 'function') {
            window.trackEvent(action, category, label, value);
        }
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.videoExtractor = new VideoExtractor();
});